package com.nf.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.nf.dao.StudentDao;
import com.nf.dao.StudentsDaoImpl;
import com.nf.entity.Students;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet("/DeleteStu")
public class DeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("delete来了");
        //设置请求字符类型
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        //接收客户端页面传递的参数
        int id =Integer.parseInt( request.getParameter("id"));
        //调用dao层的方法删除学生
        StudentDao dao = new StudentsDaoImpl();
        int result = dao.delete(id);
        System.out.println(result);
        //重新查一遍打印回客户端
        List<Students> studentsList = dao.queryAll();
        //创建一个Jackson对象
        ObjectMapper obj = new ObjectMapper();
        //定义一个日期格式模板
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //设置Jackson日期格式在链式将学生集合转换成json对象并通过response.getWriter对象打印给页面
        response.getWriter().print(obj.setDateFormat(simpleDateFormat).writeValueAsString(studentsList));
//      //使用Gson将List对象转换为json对象
//      Gson gson = new Gson();
//      response.getWriter().print(gson.toJson(studentsList));

    }
}
